﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using PasteCodeTaskBase;
using Z.EntityFramework.Plus;

namespace PasteTimer
{
    /// <summary>
    /// 
    /// </summary>
    public class CollectHandler : IPasteCodeTaskBase
    {

        private IServiceProvider _serviceProvider;
        private ILogger<ReportHandler> _logger;
        private readonly TaskConfig _config;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="config"></param>
        /// <param name="logger"></param>
        public CollectHandler(
            IServiceProvider serviceProvider,
            IOptions<TaskConfig> config,
            ILogger<ReportHandler> logger)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
            _config = config.Value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string LocationTickRegex()
        {
            return "(.*)03:00:00";
        }

        public override bool IsLocationService()
        {
            return _config.SingleModel;
        }


        /// <summary>
        /// 
        /// </summary>
        public override void Dispose()
        {
            base.Dispose();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public override async Task<PasteTaskCallBackModel> Work(PasteTaskSharedModel info)
        {
            try
            {
                var nowdate = DateTime.Now.AddDays(-7);
                using var _scope = _serviceProvider.CreateScope();
                using var _dbContext = _scope.ServiceProvider.GetRequiredService<IPasteTimerDbContext>();
                //任务记录
                await _dbContext.TaskLog.Where(x => x.CreateDate < nowdate).DeleteAsync();
                //任务报表
                await _dbContext.ReportInfo.Where(x => x.DataType == 0 && x.DataDate < nowdate).DeleteAsync();
                //推送日志
                await _dbContext.NoticeLog.Where(x => x.CreateDate < nowdate).DeleteAsync();
                _dbContext.Dispose();
                _scope.Dispose();
            }
            catch (Exception exl)
            {
                _logger.LogException(exl);
            }
            return new PasteTaskCallBackModel();
        }
    }
}
